<template>
  <BottomDrawer
    :visible="addVisible"
    :title="dataType.dataType === 0 ? '角色管理' : '角色管理'"
    :width="553"
    @close="addVisible = false"
  >
    <div v-if="addVisible" style="height:500px;overflow: auto;padding-right: 10px;">
      <el-form
        ref="pageForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
        :label-position="'left'"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="20个字符以内" />
        </el-form-item>
        <el-form-item label="模块权限" prop="menuIdList">
          <div>
            <div>
              <el-checkbox v-model="checked1" label="全选" @change="checkFun" />
            </div>
            <el-tree
              v-model="formData.menuIdList"
              ref="treeRef"
              class="filter-tree"
              node-key="menuId"
              show-checkbox
              :data="treeData"
             
              :default-checked-keys="formData.menuIdList"
              :props="defaultProps"
              default-expand-all
              :filter-node-method="filterNode"
              @check="handleCheck"
            />
          </div>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
      <el-button @click="addVisible = false">取 消</el-button>
    </template>
  </BottomDrawer>
</template>

<script setup lang="ts">
import type { RoleForm, RoleQuery } from '@/types/role';
import type { FormRules, ElTree } from 'element-plus';
import { getMenuList } from '@/api/account';
import { addRole, editRole, getMenuIdListByRole } from '@/api/clinic';
import { ref } from 'vue';
const checked1 = ref(false);
const rules = reactive<FormRules<RoleForm>>({
  roleName: [{ required: true, message: '请输入角色名称' }],
  menuIdList: [{ required: true, message: '请选择权限' }],
});
const defaultProps = {
  children: 'children',
  label: 'menuName',
};
interface Tree {
  [key: string]: any;
}
// 获取序列列表
const permissionsId = ref([]);
const emits = defineEmits(['refresh']);
const pageForm = ref();
const dataType = defineProps<{ dataType: Number }>();
const treeRef = ref<InstanceType<typeof ElTree>>();


const checkFun = ()=>{
  const tree = treeRef.value;
  if (tree) {
    if (checked1.value == true) {
      const nodes = tree.store.nodesMap; // 获取所有节点对象集合（包括叶子节点和父节点）
      Object.keys(nodes).forEach((key) => {
        // 遍历所有节点键值对
        const node = nodes[key]; // 获取节点实例对象
        if (node && !node.disabled) {
          // 如果节点未被禁用，则设置选中状态为 true
          node.setChecked(true, true); // 第二个参数 true 表示递归设置子节点也为选中状态
        }
      });
      handleCheck()
    } else {
      tree.setCheckedNodes([]);
      formData.value.menuIdList = []
    }
  }
}

const filterNode = (value: string, data: Tree) => {
  if (!value) {
    return true;
  }
  return data.name.includes(value);
};
//获取菜单
const getMenuListApi = async () => {
  const res = await getMenuList();
   if(res.code != '200'){
            //ElMessage.error(res.msg);
            return
        }
  let menuListDatas: any[] = [];
  res.data.forEach((item: any) => {
    menuListDatas.push(item);
  });
  treeData.value = menuListDatas;
};
getMenuListApi();
const treeData = ref<any[]>([]);
const addVisible = ref(false);

const formData = ref<RoleForm>({
  roleId: null,
  roleName: '',
  menuIdList: [],
  isEnabled: '0',
});
defineExpose<{
  open: () => void;
  open1: (menu: RoleForm) => void;
}>({
  open: () => {
    formData.value.menuIdList = [];
    formData.value.roleName = '';
    formData.value.roleId = null;
    checked1.value = false;
    addVisible.value = true;
  },
  open1: (menu: RoleForm) => {
    checked1.value = false;
    formData.value.roleName = menu.roleName;
    formData.value.isEnabled = menu.isEnabled;
    formData.value.roleId = menu.roleId;
    getMenuIdListByRoleApi();
  },
});
const parentId = ref<any>([]) 

const getMenuIdListByRoleApi = async () => {
  const res = await getMenuIdListByRole(formData.value.roleId);
   if(res.code != '200'){
      //ElMessage.error(res.msg);
      return
  }
  formData.value.menuIdList = res.data;
  addVisible.value = true;
  
  setTimeout(() => {
    if (treeRef.value) {
      let num = 0;
      let num2 = 0;
      const nodes = treeRef.value.store.nodesMap;
       //半勾选的节点
      parentId.value = treeRef.value!.getHalfCheckedKeys();
      if(treeRef.value!.getCheckedKeys().length > res.data.length ){
        formData.value.menuIdList = treeRef.value!.getCheckedKeys();
      }
      Object.keys(nodes).forEach((key) => {
        // 遍历所有节点键值对
        const node = nodes[key]; // 获取节点实例对象
        num += 1;
        if (node && node.checked) {
          // 如果节点未被禁用，则设置选中状态为 true
          num2 += 1;
        }
      });
      if (num != num2) {
        checked1.value = false;
      } else {
        checked1.value = true;
      }
    }

  }, 1000);
};

const handleCheck = () => {
  //勾选的节点
  const checkedNodes = treeRef.value!.getCheckedNodes();
  //半勾选的节点
  parentId.value = treeRef.value!.getHalfCheckedKeys();
  // 直接使用Set来处理formData.value.permissions，确保唯一性
  const parentKeysSet: any = [];
  // const parentIdSet: Set<any> = new Set();
  // 遍历勾选的节点
  checkedNodes.forEach((node: any) => {
    // 如果节点有父节点，并且父节点的key不在Set中，则添加到Set中
    if (node.menuId) {
      parentKeysSet.push(node.menuId);
    }
  });
  
 
  formData.value.menuIdList = parentKeysSet;
  if (treeRef.value) {
    let num = 0;
    let num2 = 0;
    const nodes = treeRef.value.store.nodesMap;
    Object.keys(nodes).forEach((key) => {
      // 遍历所有节点键值对
      const node = nodes[key]; // 获取节点实例对象
      num += 1;
      if (node && node.checked) {
        // 如果节点未被禁用，则设置选中状态为 true
        num2 += 1;
      }
    });
    if (num != num2) {
      checked1.value = false;
    } else {
      checked1.value = true;
    }
  }
};
const addChannelApi = async () => {
  let data = JSON.parse(JSON.stringify(formData.value));
  //console.log(parentId.value,'parentId.value');
  
  parentId.value.forEach((item: any) => {
    if (item) {
      data.menuIdList.push(item);
    } 
  });
  let res = await addRole(data);
  if (res.code === '200') {
    ElMessage.success(res.msg);
    emits('refresh');
    addVisible.value = false;
  } else {
    //ElMessage.error(res.msg);
  }
};
const editChannelApi = async () => {
  //console.log(parentId.value);

  let data = JSON.parse(JSON.stringify(formData.value));
  parentId.value.forEach((item: any) => {
    if (item) {
      data.menuIdList.push(item);
    }
  });
  let res = await editRole(data);
  if (res.code === '200') {
    ElMessage.success(res.msg);
    emits('refresh');
    addVisible.value = false;
  } else {
    //ElMessage.error(res.msg);
  }
};
const handleSubmit = async () => {
  const ruleFormRef = pageForm.value;
  await ruleFormRef.validate((valid: any, fields: any) => {
    if (valid) {
      if (dataType.dataType === 0) {
        addChannelApi();
      } else {
        editChannelApi();
      }
    } else {
      //console.log('error submit!', fields);
    }
  });
};

const getRoleMenu = async () => {};
onMounted(() => {});
</script>
<style lang="scss" scoped></style>
